package com.labofjet.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 获取spring容器
 * 
 * @author jyzjyz12@163.com
 * 
 */
@Service
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SpringContextUtils implements ApplicationContextAware, InitializingBean {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * beanname和applicationContext正确的情况下有bean就取,没有返回null
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        if (beanName == null || applicationContext == null) {
            throw new IllegalArgumentException("beanName或者applicationContext为空");
        }
        if (applicationContext.containsBean(beanName)) {
            return applicationContext.getBean(beanName);
        } else {
            return null;
        }
    }

    /**
     * clazz和applicationContext正确的情况下有bean就取,没有报错
     * @param clazz
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        if (clazz == null || applicationContext == null) {
            throw new IllegalArgumentException("class或者applicationContext为空");
        }
        return applicationContext.getBean(clazz);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println();
    }
}
